﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Koonsoft.HYCRM.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.HYCRM.DAL
{
    public class RoleDAL
    {
        private Database database = DatabaseFactory.CreateDatabase("KOONCRMDB");

        /// <summary>
        /// 根据登录名获取角色ID
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int GetRoleIDByLoginName(string loginName)
        {
            const string sql = "Empolyee_GetRoleIDByLoginName";

            using (var cmd = database.GetStoredProcCommand(sql))
            {
                database.AddInParameter(cmd, "@loginName", DbType.String, loginName);

                return Convert.ToInt32(database.ExecuteScalar(cmd));
            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public List<RoleInfo> GetRoles()
        {
            var roles = new List<RoleInfo>();
            
            const string procedure = "Role_GetRoles";

            using (var cmd = database.GetStoredProcCommand(procedure))
            {
                var rd = (RefCountingDataReader)database.ExecuteReader(cmd);

                var sqlrd = (SqlDataReader)rd.InnerReader;

                while (sqlrd.Read())
                {
                    var role = new RoleInfo()
                    {
                        RoleID = Convert.ToInt32(sqlrd["RoleID"]),
                        RoleName = sqlrd["RoleName"].ToString()
                    };

                    roles.Add(role);
                }
            }

            return roles;
        }
    }
}
